const mongoose = require('mongoose');
const Counter = require('./counter');
const dayjs = require('dayjs');
const { Schema } = mongoose

const RoleSchema = new Schema({
  role_id: {
    type: Number,
    unique: true,
    description: '角色id'
  },
  name: {
    type: String,
    unique: true,
    required: true,
    description: '角色名称'
  },
  code: {
    type: String,
    unique: true,
    required: true,
    description: '角色编码，用于系统标识'
  },
  description: {
    type: String,
    required: false,
    description: '角色描述'
  },
  menu_list: {
    type: Array,
    default: [],
    description: '菜单列表'
  },
  created_by: {
    type: Number,
    default: null,
    description: '创建者id'
  },
  updated_by: {
    type: Number,
    default: null,
    description: '最后更新者id'
  },
  created_at: {
    type: String,
    default: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '创建时间'
  },
  updated_at: {
    type: String,
    default: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '最后更新时间'
  }
})

RoleSchema.pre('save', async function(next) {
  if(this.isNew) {
    try {
      const counter = await Counter.findByIdAndUpdate(
        { _id: 'role_id' },
        { $inc: { seq: 1 } },
        { new: true, upsert: true }
      );
      this.role_id = counter.seq;
      next();
    } catch (error) {
      next(error);
    }
  } else {
    next();
  }
});

RoleSchema.pre('updateOne', async function(next) {
  this.set({ updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss') });
  next();
});

const roleModel = mongoose.model('role', RoleSchema, 'role')

module.exports = roleModel